<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-5-20
 * Time: 10:02
 */

namespace doumiaoduo\ueditor;


use yii\widgets\InputWidget;
use yii\helpers\Html;
use yii\helpers\Json;

class ImageUpload extends InputWidget{


    public $clientOptions = [];

    public $serverParam=[];

    public $buttonOptions = [];

    public function init(){
        parent::init();
        $id=str_replace('-','_',$this->options['id']);
        if(isset($this->clientOptions['serverUrl'])){
            $this->clientOptions['serverUrl']=str_replace('action','',$this->clientOptions['serverUrl']);
            $this->clientOptions['serverUrl']=str_replace(urlencode('action'),'',$this->clientOptions['serverUrl']);
        }
        $this->clientOptions['csrf-param']=\Yii::$app->request->csrfParam;
        $this->clientOptions['csrf-token']=\Yii::$app->request->getCsrfToken();
        $this->clientOptions['isShow']=false;
        $this->buttonOptions['id']=isset($this->buttonOptions['id'])?$this->buttonOptions['id']:"image_upload_button_{$this->options['id']}";
        $this->buttonOptions['class']="zx_upload_button";
    }

    public function run()
    {
        $strHtml='';
        if($this->hasModel()){
            $strHtml.=Html::activeTextInput($this->model,$this->attribute,$this->options);
        }
        else{
            $strHtml.=Html::textInput($this->name,$this->value,$this->options);
        }
        $strHtml.=Html::buttonInput('上传图片',$this->buttonOptions);
        echo $strHtml;
        $this->registerClientScript();
    }

    public function registerClientScript(){
        $view = $this->getView();
        UeditorAsset::register($view);
        $options=Json::htmlEncode($this->clientOptions);
        $id=str_replace('-','_',$this->options['id']);
        $js="var image_upload_editor_{$id} = UE.getEditor('{$this->buttonOptions['id']}',$options); \n";
        $js.="jQuery('#{$this->buttonOptions['id']}').on('click',function(){image_upload_editor_{$id}.getDialog('insertimage').open();});\n";
        $js.="image_upload_editor_{$id}.ready(function() { \n";
        if(!empty($this->serverParam)){
            $params=Json::htmlEncode($this->serverParam);
            $js.="alert($params)";
            $js.="image_upload_editor_{$id}.execCommand('serverparam', function(editor) { \n";
            $js.="return {$params}; \n";
            $js.="}); \n";
        }
        $js.="image_upload_editor_{$id}.addListener('beforeInsertImage', function (t,arg){ \n";
        $js.="if(arg.length==1){ \n";
        $js.="document.getElementById('{$this->options['id']}').value = arg[0].src";
        $js.="}else{ \n";
        $js.="alert('请选择一张图片'); \n";
        $js.="}}); \n";
        $js.="}); \n";
        $view->registerJs($js);
    }

}